package com.sx.manage.controller.relation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.biz.relation.IMRelationConfigBiz;
import com.sx.manage.controller.base.MBaseController;
import com.sx.manage.service.consumer.IMBaseCompanyConsumerInfoService;
import com.sx.manage.service.consumer.IMCompanyConsumerInfoService;
import com.sx.manage.service.consumer.IMSystemConsumerInfoService;
import com.sx.manage.service.relation.IMBaseRelationConfigService;
import com.sx.manage.service.relation.MWebRelationServiceImpl;
import com.sx.manage.service.role.IMBaseRoleInformationService;
import com.sx.model.constants.MDataStatusType;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.relation.MRelationForm;
import com.sx.model.manage.mybatis.form.role.MRoleForm;
import com.sx.model.manage.mybatis.vo.consumer.company.MComConsumerVO;
import com.sx.model.manage.mybatis.vo.function.MFunctionInfoVO;
import com.sx.model.manage.mybatis.vo.relation.MRelationConfigVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.role.MRoleVO;
import com.sx.model.util.StringsUtil;

@Controller
@RequestMapping("/relation")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class MRelationController extends MBaseController {
	/**
	 * 日志
	 */
	private Logger _log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "mBaseRoleInfoServiceImpl")
	private IMBaseRoleInformationService mBaseRoleInfoServiceImpl;

	@Resource(name = "systemConsumerInfoServiceImpl")
	private IMSystemConsumerInfoService systemConsumerInfoServiceImpl;

	@Resource(name = "mCompanyConsumerInfoServiceImpl")
	public IMCompanyConsumerInfoService mCompanyConsumerServiceImpl;

	@Resource(name = "mBaseCompanyConsumerInfoServiceImpl")
	public IMBaseCompanyConsumerInfoService mBaseCompanyConsumerInfoServiceImpl;

	@Resource(name = "mRelationConfigBizImpl")
	public IMRelationConfigBiz mRelationConfigBizImpl;
	// 系统关系 service
	@Resource(name = "mBaseRelationConfigServiceImpl")
	public IMBaseRelationConfigService mBaseRelationConfigServiceImpl;

	// 关系service
	@Resource(name = "webRelationServiceImpl")
	public MWebRelationServiceImpl webRelationServiceImpl;

	/**
	 * 根据roleId 获取 关系信息
	 * 
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "listByRoleId")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> listByRoleId(Long roleId) {
		if (null == roleId) {
			return new ResultListVO<>("m.parameter.is.null");
		}
		return this.mBaseRelationConfigServiceImpl.queryListByRoleId(roleId);
	}

	/**
	 * 增加角色与模块关联关系
	 * 
	 * @param roleId
	 * @param moduleIds
	 * @return
	 */
	@RequestMapping(value = "role2Mod")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> role2Mod(Long roleId, String[] function_ids) {
		// 增加角色与模块关联关系
		return this.mRelationConfigBizImpl.save(roleId, function_ids, MSystemConstants.RELA_ROLE_FUNCTION, loginConsumer());
	}

	/**
	 * 增加角色与模块,按钮的关联关系
	 * 
	 * @param roleId
	 * @param moduleIds
	 * @return
	 */
	@RequestMapping(value = "role2FunctionAndButton")
	@ResponseBody
	public ResultBooleanVO role2FunctionAndButton(Long roleId, String[] function_ids, String[] function_button_ids) {
		if (null == roleId || null == function_ids) {
			return new ResultBooleanVO("m.parameter.is.null");
		}
		// 增加角色与模块关联关系
		return this.mRelationConfigBizImpl.role2Func2Button(roleId, function_ids, function_button_ids, loginConsumer());
	}

	/**
	 * 增加角色 与公司关系
	 * 
	 * @param roleId
	 * @param companyIds
	 * @return
	 */
	@RequestMapping(value = "role2Companys")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> role2Companys(Long roleId, String[] companyIds) {
		// 角色与公司的关系
		return this.mRelationConfigBizImpl.save(roleId, companyIds, MSystemConstants.RELA_COMAPNY_ROLE, loginConsumer());
	}


	/**
	 * 增加角色与用户关系
	 * 
	 * @param roleIds
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "role2User")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> role2User(Long[] roleIds, String userId) {
		// 角色与用户的关系
		return this.mRelationConfigBizImpl.save(roleIds, userId, MSystemConstants.RELA_PERSON_CONSUMER_ROLE, loginConsumer(), null);
	}

	/**
	 * 根据 role 删除关联关系
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "deleteByRoleId")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> deleteByRoleId(Long id) {

		return this.mRelationConfigBizImpl.editStatusByRoleId(id, loginConsumer());
	}

	/**
	 * 机构配置角色 展示列表数据
	 * 
	 * @param roleId
	 * @param roleType
	 * @return
	 */
	@RequestMapping(value = "listForConfigCompany")
	@ResponseBody
	public ResultListVO<MRoleVO> listForConfigCompany(Long companyId) {

		ResultListVO<MRoleVO> ListResult = new ResultListVO<>();
		// 获取公司配置的角色
		MRelationForm relationForm = new MRelationForm();
		relationForm.setCompany_id(companyId);
		relationForm.setRelation_type(MSystemConstants.RELA_COMAPNY_ROLE);

		List<MRelationConfigVO> relaList_ = mBaseRelationConfigServiceImpl.queryList(relationForm);
		/// 获取全部角色
		MRoleForm form = new MRoleForm();
		form.setRole_type(MSystemConstants.RELA_COMAPNY_ROLE);

		List<MRoleVO> allRoleList = this.mBaseRoleInfoServiceImpl.queryList(form, loginConsumer()).getData();
		// 选中已经配置的角色
		for (MRoleVO role_ : allRoleList) {
			for (MRelationConfigVO rela_ : relaList_) {
				if (rela_.getRole_id().equals(role_.getId())) {
					role_.setCheck_status(MSystemConstants.NO_);
					break;
				}
			}
		}
		ListResult.setData(allRoleList);
		return ListResult;
	}

	/**
	 * 角色 配置模块 列表展示关系
	 * 
	 * @param roleId
	 * @param roleType
	 * @return
	 */
	@RequestMapping(value = "role2listForConfig")
	@ResponseBody
	public ResultListVO<MFunctionInfoVO> role2listForConfig(Long roleId, String roleType) {
		_log.debug("role2listForConfig controller调用");
		return webRelationServiceImpl.role2listForConfig(roleId, roleType);
	}

	/**
	 * 根据用户id 获取 关系列表
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "listByUserId")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> listByUserId(Long userId) {

		return this.mBaseRelationConfigServiceImpl.queryListByConsumer(userId, null, loginConsumer());
	}

	/**
	 * 增加用户 与角色 关联关系
	 * 
	 * @param userId
	 * @param relationType
	 * @param roleIds
	 * @return
	 */
	@RequestMapping(value = "user2Role")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> user2Role(Long userId, String relationType, String[] roleIds) {
		// 用户 与角色关联
		return this.mRelationConfigBizImpl.save(userId, relationType, roleIds, loginConsumer());
	}

	/**
	 * 增加 渠道 与角色 关联关系
	 * 
	 * @param channel_id
	 * @param relationType
	 * @param roleIds
	 * @return
	 */
	@RequestMapping(value = "business2Role")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> business2Role(Long business_id, String[] roleIds) {

		// 用户 与角色关联
		return this.mRelationConfigBizImpl.save(business_id, MSystemConstants.RELA_BUSINESS_ROLE, roleIds, loginConsumer());
	}

	/**
	 * 增加系统用户角色配置
	 * 
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	@RequestMapping(value = "sysConsumer2Role")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> sysConsumer2Role(Long consumer_id, String[] role_ids) {
		// 系统用户角色配置
		return this.mRelationConfigBizImpl.saveForSysConsumer(consumer_id, role_ids, loginConsumer());
	}



	/**
	 * 公司用户关系获取
	 * 
	 * @param userId
	 * @return
	 */

	@RequestMapping(value = "companyUser2listForConfig")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> companyUser2listForConfig(Long userId) {

		try {
			// 查询公司用户信息
			MComConsumerVO user = this.mBaseCompanyConsumerInfoServiceImpl.get_companyConsumer_byId(userId).getObjVo();
			if (null == user) {
				return new ResultListVO<>("m.user.not.exist");
			}
			// 用户关系
			ResultListVO<MRelationConfigVO> reslut = this.mBaseRelationConfigServiceImpl.queryListByConsumer(userId, MSystemConstants.RELA_COMPANY_CONSUMER_ROLE, loginConsumer());
			List<MRelationConfigVO> userRela = reslut.getData();
			/// 角色
			MRoleForm form = new MRoleForm();
			// 公司用户能获取就是公司用户
		    form.setRole_type( MSystemConstants.ROLE_TYPE_COMPANY );
			form.setData_status(MDataStatusType.DATA_AVAILABLE);

			ResultListVO roleListResult = new ResultListVO();
			/// 获取可以配置的角色信息
			List<MRoleVO> roleList = this.mBaseRoleInfoServiceImpl.queryListForComConfig(user, form);
			if (null == roleList) {
				return null;
			}
			// 角色树，勾选状态
			for (MRoleVO roleVO : roleList) {
				for (MRelationConfigVO relationVO : userRela) {
					if (relationVO.getRole_id() != null && relationVO.getRole_id().equals(roleVO.getId())
							&&user.getCompany_id().equals(relationVO.getCompany_id())) {
						roleVO.setCheck_status(MSystemConstants.NO_);
					}
				}
			}
			roleListResult.setData(roleList);
			return roleListResult;
		} catch (Exception e) {
			_log.error("公司用户关系获取error={}",e);
		}
		return null;
	}

	/**
	 * 系统用户分配权限
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "listSystemConsumerForConfig")
	@ResponseBody
	public ResultListVO listSysForConfig(Long consumer_id) {
		return webRelationServiceImpl.listRoleForSysConsumerConfig(consumer_id, this.loginConsumer());
	}

	/**
	 * 系统用户分配权限
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "listBusinessForConfig")
	@ResponseBody
	public ResultListVO<MRoleVO> listBusinessForConfig(Long business_id) {
		_log.debug(" controller 方法 listSupplierForConfig 调用 business_id=" + business_id);
		return this.webRelationServiceImpl.getRoleListForBusinessConfig(business_id);
	}

	/**
	 * 机构配置角色
	 * 
	 * @param roleId
	 * @param roleType
	 * @return
	 */
	@RequestMapping(value = "listForConfigUserCompany")
	@ResponseBody
	public ResultListVO<MRoleVO> listForConfigCompany(Long userId, Long comId) {
		ResultListVO<MRoleVO> listResult = new ResultListVO<>();

		List<MRelationConfigVO> relaList_ = this.mBaseRelationConfigServiceImpl.queryListForConsumerManageCompany(userId, comId);

		/// 获取全部角色
		MRoleForm form = new MRoleForm();
		form.setRole_type(MSystemConstants.ROLE_TYPE_COMPANY);
		form.setCompany_id(comId);
		List<MRoleVO> allRoleList = this.mBaseRoleInfoServiceImpl.queryList(form, loginConsumer()).getData();
		// 选中已经配置的角色
		List<MRoleVO> comRoleList = new ArrayList<>();
		for (MRoleVO role_ : allRoleList) {
			_log.debug("属于公司的角色，或者没有所属公司的角色加入");
			if (null == role_.getCompany_id() || role_.getCompany_id().equals(comId)) {
				_log.debug("已经配置的选中");
				for (MRelationConfigVO rela_ : relaList_) {
					if (rela_.getRole_id().equals(role_.getId())) {
						role_.setCheck_status(MSystemConstants.NO_);
						break;
					}
				}
				comRoleList.add(role_);
			}
		}
		listResult.setData(comRoleList);
		return listResult;
	}
	/**
	 * 配置公司用户与角色的关系
	 * 
	 * @param roleIds
	 * @param companyId
	 * @return
	 */
	@RequestMapping(value = "roles2Company")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> roles2Company(Long[] roleIds, String companyId, Long userId) {
		if (userId == null) {
			return new ResultListVO("m.parameter.is.null");
		}
		if (null == companyId) {
			MComConsumerVO comUser = this.mBaseCompanyConsumerInfoServiceImpl.get_companyConsumer_byId(userId).getObjVo();
			companyId = String.valueOf(comUser.getCompany_id());
		}
		// 角色与公司的关系
		return this.mRelationConfigBizImpl.save(roleIds, companyId, MSystemConstants.RELA_COMPANY_CONSUMER_ROLE, loginConsumer(), userId);
	}
	/**
	 * 增加公司用户 管理的公司及角色信息
	 * 
	 * @param userId
	 * @param companyId
	 * @param roleIds
	 * @return
	 */
	@RequestMapping(value = "user2Company2Role")
	@ResponseBody
	public ResultListVO<MRelationConfigVO> user2Company2Role(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		String requestMessage = extractParamFromRequest(req);
		if (StringUtils.isBlank(requestMessage)) {
			return null;
		}

		Map map = JackJsonUtil.jsonToMap(requestMessage, String.class, String.class);

		Long userId = Long.valueOf(map.get("id").toString());
		Long companyId = Long.valueOf(map.get("comId").toString());
		String roleId = map.get("roleIds").toString();
		Long[] roleIds = StringsUtil.StringtoLong(roleId);
		// 角色关联
		// 删除之前 公司-用户 的权限
		// 数据入库
		return this.mRelationConfigBizImpl.save(userId, companyId, roleIds, loginConsumer());
	}

}
